package app.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import app.dao.UserDAO;
import app.utils.Utils;
import app.entity.User;

@WebServlet(name = "register", urlPatterns = { "/register" })
public class Register extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public Register() {
        super();
       
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password").trim();
		String confirm = request.getParameter("confirm").trim();
		
		if (!UserDAO.isExistUsername(username) &&
				Utils.checkConfirmPassword(password, confirm)) {
			User newUser = new User();
			newUser.setUsername(username);
			newUser.setPassword(password);
			UserDAO.addNewUser(newUser);
			
			HttpSession session = request.getSession();
			session.setAttribute("username", username);
			
			request.getRequestDispatcher("/create_card.jsp").forward(request, response);
			
		}
		
	}

}
